package com.example.cursor.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.cursor.common.Result;
import com.example.cursor.dto.TransferDTO;
import com.example.cursor.entity.Account;
import com.example.cursor.entity.TransactionRecord;
import com.example.cursor.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/accounts")
public class AccountController {

    @Autowired
    private AccountService accountService;

    // 创建账户
    @PostMapping
    public ResponseEntity<Account> create(@RequestBody Account account) {
        accountService.save(account);
        return ResponseEntity.ok(account);
    }

    // 根据ID查询账户
    @GetMapping("/{id}")
    public ResponseEntity<Account> getById(@PathVariable Long id) {
        return ResponseEntity.ok(accountService.getById(id));
    }

    // 分页查询账户列表
    @GetMapping
    public ResponseEntity<Page<Account>> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String username) {
        
        Page<Account> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<Account> queryWrapper = new LambdaQueryWrapper<>();
        
        if (username != null && !username.isEmpty()) {
            queryWrapper.like(Account::getUsername, username);
        }
        
        return ResponseEntity.ok(accountService.page(pageParam, queryWrapper));
    }

    // 更新账户信息
    @PutMapping("/{id}")
    public ResponseEntity<Account> update(@PathVariable Long id, @RequestBody Account account) {
        account.setId(id);
        accountService.updateById(account);
        return ResponseEntity.ok(account);
    }

    // 删除账户
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        accountService.removeById(id);
        return ResponseEntity.ok().build();
    }

    // 转账
    @PostMapping("/transfer")
    public Result<TransactionRecord> transfer(@RequestBody TransferDTO transferDTO) {
        return Result.success(accountService.transfer(transferDTO));
    }
    
    // 查询交易记录
    @GetMapping("/{accountId}/transactions")
    public Result<List<TransactionRecord>> getTransactionRecords(@PathVariable Long accountId) {
        return Result.success(accountService.getTransactionRecords(accountId));
    }
} 